﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Husb.Util;
using Husb.Util.Enum;
using CentralOffice.Task.Data;
using CentralOffice.Task.BusinessActions;

using ApplicationTable = CentralOffice.Task.Data.ApplicationDataSet.ApplicationsDataTable;
using ApplicationRow = CentralOffice.Task.Data.ApplicationDataSet.ApplicationsRow;

using ApprovalTable = CentralOffice.Task.Data.ApprovalDataSet.ApprovalsDataTable;
using ApprovalRow = CentralOffice.Task.Data.ApprovalDataSet.ApprovalsRow;
using System.Data;


namespace CentralOffice.WebClient.Tasks
{
    public partial class ApplicationView : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                string applicationId = HttpContext.Current.Request.QueryString["id"];
                ApplicationRow application = CentralOffice.Task.BusinessActions.Applications.GetById(new Guid(applicationId));

                lblApplicationCode.Text = application.IsApplicationCodeNull() ? "" : application.ApplicationCode;
                lblApplicant.Text = application.Applicant;
                lblApprovalContent.Text = application.ApprovalContent;
                lblDateOfApplication.Text = application.DateOfApplication.ToString();
                lblName.Text = application.Name;
                lblStatus.Text = EnumUtil.GetDisplayName(SiteConstants.ApprovalStatus, CategoryDataSourceType.Xml, application.Status);

                lblApplicationExecutor.Text = application.IsApplicationExecutorNull() ? "" : application.ApplicationExecutor;
                lblExecutiveDescription.Text = application.IsExecutiveDescriptionNull() ? "" : application.ExecutiveDescription;

                if (!application.IsAttachmentsNull() && application.Attachments.Length > 0)
                {
                    lblAttachments.Visible = true;
                    SiteUtil.GenernateDownloadHyperLink(lblAttachments, application.Attachments);
                }

                if (application.Version == 2)
                {
                    divPaymentList.Visible = true;
                    gvPaymentItem.Visible = true;

                    PaymentItemDataSet ds = new PaymentItemDataSet();
                    System.IO.StringReader sw = new System.IO.StringReader(application.Description);
                    ds.ReadXml(sw);

                    // 没有特殊含义，就是加一个合计行：
                    PaymentItemDataSet.PaymentRow row1 = ds.Payment.NewPaymentRow();
                    row1.Id = Guid.NewGuid();
                    row1.ApplicationId = Guid.NewGuid();
                    row1.Customer = "合计：";
                    row1.TotalDue = ds.Payment.Sum(i => i.TotalDue);
                    row1.ApprovedDue = ds.Payment.Sum(i => i.ApprovedDue);
                    row1.Subject = "";
                    row1.Remark = "";
                    row1.Status = 1;
                    row1.IsApproved = true;

                    ds.Payment.AddPaymentRow(row1);

                    DataView dv = new DataView(ds.Payment, null, " IsApproved ", DataViewRowState.CurrentRows);

                    gvPaymentItem.DataSource = dv;
                    gvPaymentItem.DataBind();

                    this.ViewState["IsWeekPlan"] = true;

                    string stepId = Request.QueryString["sid"];
                    if (!String.IsNullOrEmpty(stepId))
                    {
                        ApprovalRow approval = CentralOffice.Task.BusinessActions.Approvals.GetById(new Guid(stepId));

                        divItem.Visible = true;
                        gvItem.Visible = true;

                        PaymentItemDataSet items = new PaymentItemDataSet();
                        System.IO.StringReader sw2 = new System.IO.StringReader(approval.Description);
                        items.ReadXml(sw2);

                        // 没有特殊含义，就是加一个合计行：
                        PaymentItemDataSet.PaymentRow row2 = items.Payment.NewPaymentRow();
                        row2.Id = Guid.NewGuid();
                        row2.ApplicationId = Guid.NewGuid();
                        row2.Customer = "合计：";
                        row2.TotalDue = items.Payment.Sum(i => i.TotalDue);
                        row2.ApprovedDue = items.Payment.Sum(i => i.ApprovedDue);
                        row2.Subject = "";
                        row2.Remark = "";
                        row2.Status = 1;
                        row2.IsApproved = true;

                        items.Payment.AddPaymentRow(row2);

                        DataView dv2 = new DataView(items.Payment, null, " IsApproved ", DataViewRowState.CurrentRows);

                        gvItem.DataSource = dv2;
                        gvItem.DataBind();
                    }
                    else
                    {
                        divItem.Visible = false;
                        gvItem.Visible = false;
                    }
                    
                }
                else
                {
                    this.ViewState["IsWeekPlan"] = false;
                }
            }
        }

        protected void gvApproval_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ApprovalRow approval = ((DataRowView)e.Row.DataItem).Row as ApprovalRow;

                if (e.Row.Cells[6].Text.Length > 40)
                {
                    e.Row.Cells[6].Text = e.Row.Cells[6].Text.Substring(0, 40) + "...";
                }

                if ((bool)this.ViewState["IsWeekPlan"] && !approval.IsDateApprovedNull())
                {
                    string old = Request.Url.ToString();
                    if (old.IndexOf("&sid=") > 0)
                    {
                        old = old.Substring(0, old.IndexOf("&sid="));
                    }
                    string a = "<a href='" + old + "&sid=" + approval.Id.ToString() + "'> [详细内容]</a>";
                    e.Row.Cells[6].Text = e.Row.Cells[6].Text + a;
                }

                // 审批结果
                if (approval[(approval.Table as ApprovalTable).DateApprovedColumn.ColumnName] != DBNull.Value)
                {
                    if (approval.ResultApproved)
                    {
                        e.Row.Cells[7].Text = "通过";
                    }
                    else
                    {
                        e.Row.Cells[7].Text = "<span class=\"warning\">否决</span>";
                    }
                }
                // 附件
                if (!approval.IsApprovalAttachmentsNull())
                {
                    HyperLink link = e.Row.Cells[8].Controls[0] as HyperLink;
                    SiteUtil.GenernateDownloadHyperLink(link, approval.ApprovalAttachments);
                }
                //else
                //{
                //    link = e.Row.Cells[7].Controls[0] as HyperLink;
                //    SiteUtil.GenernateDownloadHyperLink(link, approval.ApprovalAttachments);
                    
                //}
                // 上步审批结果
                if (approval[(approval.Table as ApprovalTable).PreviousDateApprovedColumn.ColumnName] != DBNull.Value)
                {
                    if (approval.PreviousResultApproved)
                    {
                        e.Row.Cells[11].Text = "通过";
                    }
                    else
                    {
                        e.Row.Cells[11].Text = "<span class=\"warning\">否决</span>";
                    }
                }

                
                // 是否有权审批
                if (approval.ApprovedBy == CommonUtil.TrimAll(ApplicationContext.ActualUserName) && approval[(approval.Table as ApprovalTable).DateApprovedColumn.ColumnName] == DBNull.Value)
                {
                    e.Row.Cells[13].Controls[0].Visible = false; ;
                }
                else
                {
                    e.Row.Cells[13].Controls[0].Visible = false;
                }

                //SiteUtil.SetElapsedTime(e, 12, approval.IsElapsedTimeNull() ? 0: approval.ElapsedTime);
                //e.Row.Cells[12].Text = SiteUtil.GetDateTimeString((approval.IsDateApprovedNull() ? DateTime.Now : approval.DateApproved) - approval.CreatedTime);
                // 审批时长
                if (approval.IsDateApprovedNull())
                {
                    e.Row.Cells[12].Text = "";
                }
                else
                {
                    DateTime approvedDate = approval.IsDateApprovedNull() ? DateTime.Now : approval.DateApproved;
                    e.Row.Cells[12].Text = SiteUtil.GetDateTimeString(approvedDate - approval.CreatedTime, (approval.IsWarningDateNull() ? DateTime.Now : approval.WarningDate) < approvedDate);
                }

                //e.Row.Cells[6].Text = approval.IsOpinionNull() ? "" : approval.Opinion.Replace("\r\n", "<br />");

            }
        }

        protected void gvPaymentItem_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.Cells[5].Text.ToLower() == "true")
                {
                    e.Row.Cells[5].Text = "同意";
                }
                else
                {
                    //e.Row.Cells[5].Text = "不同意";
                    e.Row.Cells[5].Text = "<span class=\"warning\">不同意</span>";
                }

                var num1 = Convert.ToDecimal( e.Row.Cells[3].Text);
                var num2 = Convert.ToDecimal(e.Row.Cells[4].Text);

                if (num1 > num2)
                {
                    e.Row.Cells[4].Text = "<span class=\"warning\">" + e.Row.Cells[4].Text + "</span>";
                }


            }
        }

        //protected void gvPaymentItem_RowDataBound(object sender, GridViewRowEventArgs e)
        //{
        //}
    }
}
